import React from "react"
// import './index.scss'
import { API } from "../../utils/api"
import styles from './index.module.css'
import SearchHeader from "../../components/SearchHeader" //搜索栏组件
import { Flex } from "antd-mobile"
import Filter from "./components/Filter"  //筛选栏组件
import { List, WindowScroller, AutoSizer, InfiniteLoader } from 'react-virtualized';  //长列表组件
import HouseItem from "../../components/HouseItem"  //渲染每一行的数据
import { BASE_URL } from "../../utils/url"
import { Toast } from 'antd-mobile';
import Sticky from '../../components/Sticky'  //导入吸顶组件
import NoHouse from '../../components/NoHouse'  //导入没有房源组件
import { getCurrentCity } from '../../utils'  //导入本地城市
// const { value } = JSON.parse(localStorage.getItem('hkzf_city'))
export default class HoseList extends React.Component {
    state = {

        list: [],
        count: 0,
        isLoading: false, //判断是否有房源  数据是否加载中

    }
    // 初始化数据
    label = ''
    value = ''
    // 初始化属性
    filters = {};
    async componentDidMount() {
        const { label, value } = await getCurrentCity()  //解决切换城市 数据不更新需要手动更新的bug
        this.label = label;
        this.value = value
        //获取数据
        this.searchHouseList();
    }
    componentWillUnmount() {
        this.setState = () => false;   //解决刷新bug
    }
    //子组件调用的方发获取数据
    onFilter = (filters) => {
        window.scrollTo(0, 0)  //返回页面顶部
        this.filters = filters;
        //获取房屋数据
        this.searchHouseList();
    }
    //获取房屋列表数据
    async searchHouseList() {
        this.setState({ isLoading: true });
        Toast.loading('数据加载中...', 1, null, false);
        const res = await API.get('/houses', {
            params: {
                cityId: this.value,
                ...this.filters,
                start: 1,
                end: 20
            }
        })
        const { list, count } = res.data.body;
        Toast.hide();
        if (count !== 0) {
            Toast.info(`共找到${count}套房源`, 2, null, false)
        }
        this.setState({
            list: list,
            count: count,
            isLoading: false
        });

    }

    // List渲染每一行的方法
    renderHouseList = ({
        key, // Unique key within array of rows
        index, // 索引号
        style   // 重点属性：一定要给每一个行数添加该样式
    }) => {
        const { list } = this.state;
        const house = list[index];
        // 如果不存在，需要渲染loading元素占位
        if (!house) {
            return (
                <div key={key} style={style}>
                    <p className={styles.loading}></p>
                </div>
            );
        }
        return (
            <HouseItem
                key={key}
                style={style}
                src={BASE_URL + house.houseImg}
                title={house.title}
                desc={house.desc}
                tags={house.tags}
                price={house.price}
            />
        );
    };

    // 判断每一行数据是否加载完毕
    isRowLoaded = ({ index }) => {
        return !!this.state.list[index];
    };
    // 用来获取更多房屋列表数据
    // 注意，该方法的返回值是一个 Promise 对象，并且，这个对象应该在数据加载完成时，来调用 resolve让 Promise对象的状态变为已完成
    loadMoreRows = ({ startIndex, stopIndex }) => {
        return new Promise(resolve => {
            API.get("/houses", {
                params: {
                    cityId: this.value,
                    ...this.filters,
                    start: startIndex,
                    end: stopIndex
                }
            })
                .then(res => {
                    // console.log(res);
                    this.setState({
                        list: [...this.state.list, ...res.data.body.list]
                    });
                    // 加载数据完成时，调用resolve即可
                    resolve();
                });
        });
    };

    //渲染列表数据
    renderList() {
        const { count, isLoading } = this.state
        if (count === 0 && !isLoading) {
            return <NoHouse>当前地区暂无房源!</NoHouse>
        }
        return (
            <InfiniteLoader
                isRowLoaded={this.isRowLoaded}
                loadMoreRows={this.loadMoreRows}
                rowCount={count}
            >
                {({ onRowsRendered, registerChild }) => (
                    <WindowScroller>
                        {({ height, isScrolling, scrollTop }) => (
                            <AutoSizer>
                                {({ width }) => (
                                    <List
                                        onRowsRendered={onRowsRendered}
                                        ref={registerChild}
                                        autoHeight // 设置高度为 WindowScroller 最终渲染的
                                        height={count * 120} // 视口高度
                                        // height={height}  //直接设置height有bug
                                        width={width} // 视口宽度
                                        rowCount={count} // List列表项总条目数
                                        rowHeight={120} // 每一行高度
                                        rowRenderer={this.renderHouseList}
                                        isScrolling={isScrolling}  //是否滚动中
                                        scrollTop={scrollTop}  //页面滚动的距离
                                    />
                                )}
                            </AutoSizer>
                        )}
                    </WindowScroller>
                )}
            </InfiniteLoader>

        )
    }
    render() {
        return (
            <div>
                {/* 顶部搜索栏 */}
                <Flex className={styles.header}>
                    <i className='iconfont icon-back' onClick={() => this.props.history.go(-1)}></i>
                    <SearchHeader cityName={this.label} className={styles.searchHeader} />
                </Flex>
                {/* 条件筛选栏 */}
                <Sticky height={44}>
                    <Filter onFilter={this.onFilter} />
                </Sticky>


                {/* 房屋列表 */}
                <div className={styles.houseItems}>
                    {this.renderList()}
                </div>
            </div >
        )
    }
}